package top.mcwebsite.playandroid.home.ui

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.playandroid.business.articles.api.model.ArticleModel
import top.mcwebsite.playandroid.common.constant.RouteConfig.ArticleDetail
import top.mcwebsite.playandroid.common.uiWidget.ErrorPage
import top.mcwebsite.playandroid.home.vm.HomePageIntent
import top.mcwebsite.playandroid.home.vm.HomePageUiEffect
import top.mcwebsite.playandroid.home.vm.HomeUiState
import top.mcwebsite.playandroid.home.vm.HomeViewModel
import top.mcwebsite.playandroid.lib.common.ext.encodeURL

@Composable
fun HomePage() {
    val viewModel: HomeViewModel = viewModel()
    viewModel.HandleUiEffect {
        when (it) {
            is HomePageUiEffect.NavigationToArticleDetailPageUiEffect -> {
                EasyRouter.navigate(ArticleDetail.PATH + "/${it.articleLink.encodeURL()}")
            }
        }
    }
    val uiState by viewModel.uiStateFlow.collectAsState()
    if (uiState.errorModel != null) {
        ErrorPage(
            errorModel = uiState.errorModel!!
        )
    } else {
        val uiState by viewModel.uiStateFlow.collectAsState()
        val lazyPagingItems = viewModel.pagerFlow.collectAsLazyPagingItems()
        HomePage(
            uiState,
            lazyPagingItems,
            onRefresh = {
                lazyPagingItems.refresh()
                viewModel.refresh()
            }, sendIntent = {
                viewModel.sendIntent(it)
            }
        )
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HomePage(
    uiState: HomeUiState,
    lazyPagingItems: LazyPagingItems<ArticleModel>,
    onRefresh: () -> Unit,
    sendIntent: (HomePageIntent) -> Unit,
) {
    val refreshing = uiState.isRefreshing
    val pullRefreshState = rememberPullRefreshState(refreshing, {
        onRefresh()
    })
    Box(
        modifier = Modifier
            .pullRefresh(pullRefreshState)
    ) {
        val listState = rememberLazyListState()
        LazyColumn(
            state = listState
        ) {
            item {
                Banner(uiState.asyncBanners) {
                    sendIntent(HomePageIntent.OnClickBannerIntent(it))
                }
            }
            if (uiState.topArticleModels.isEmpty()) {
                items(3) {
                    SkeletonItem()
                }
            } else {
                item {
                    Spacer(modifier = Modifier.height(10.dp))
                }
                items(uiState.topArticleModels.size) {
                    ArticleItemContent(model = uiState.topArticleModels[it], isPin = true) { item ->
                        sendIntent(HomePageIntent.OnClickArticleIntent(item))
                    }
                }
            }
            items(count = lazyPagingItems.itemCount) { index ->
                lazyPagingItems[index]?.let {
                    ArticleItemContent(model = it, isPin = false) { item ->
                        sendIntent(HomePageIntent.OnClickArticleIntent(item))
                    }
                }
            }
            if (lazyPagingItems.loadState.append == LoadState.Loading) {
                item {
                    CircularProgressIndicator(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentWidth(Alignment.CenterHorizontally)
                    )
                }
            }
        }
        PullRefreshIndicator(
            refreshing,
            pullRefreshState,
            Modifier.align(Alignment.TopCenter),
            scale = true
        )
    }
}

